package com.wedo.mall.activity.main;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.e.library.activity.EActivity;
import com.google.zxing.Result;
import com.wedo.mall.R;
import com.wedo.mall.activity.agent.AgentDetailActivity;
import com.wedo.mall.activity.payment.PaymentActivity;

import butterknife.BindView;
import me.dm7.barcodescanner.zxing.ZXingScannerView;

/**
 * 二维码规则
 * mitchell://receipt=xxx，跟mitchell://agentDetail=xxx
 * Created by lxy on 2017/6/19.
 */

public class ScannerActivity extends EActivity implements ZXingScannerView.ResultHandler{

    public static final String QR_CODE_RECEIPT = "receipt";
    public static final String QR_CODE_AGENT = "agentDetail";

    @BindView(R.id.xcv_scanner) ZXingScannerView xcv_scanner;

    @Override
    protected int layout() {
        return R.layout.activity_scanner;
    }

    @Override
    protected void onActivityCreated(Bundle state) {
        xcv_scanner.setResultHandler(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        xcv_scanner.startCamera();
    }

    @Override
    protected void onStop() {
        super.onStop();
        xcv_scanner.stopCamera();
    }

    @Override
    public void handleResult(Result result) {
        xcv_scanner.resumeCameraPreview(this);
        if (result == null) {
            toast(R.string.scanner_retry);
            return;
        }

        String text = result.getText();
        if(TextUtils.isEmpty(text)) {
            toast(R.string.scanner_retry);
            return;
        }

        Log.i("Scanner",text);

        if(text.contains(QR_CODE_AGENT)) {
            xcv_scanner.stopCamera();
            String id = parse(text,QR_CODE_AGENT);
            if(TextUtils.isEmpty(id)) {
                xcv_scanner.startCamera();
                return;
            }
            AgentDetailActivity.toDetail(ScannerActivity.this,id);
            defaultFinish();

        }else if(text.contains(QR_CODE_RECEIPT)) {
            xcv_scanner.stopCamera();
            String id = parse(text,QR_CODE_RECEIPT);
            if(TextUtils.isEmpty(id)) {
                xcv_scanner.startCamera();
                return;
            }
            PaymentActivity.toPayment(ScannerActivity.this,id);
            defaultFinish();
        }else {
            toast(R.string.scanner_retry);
        }
    }

    /**
     * 解析扫描结果
     * @param text
     * @param type
     * @return
     */
    private String parse(String text,String type){
        try{
            int index = text.indexOf(type);
            int offset = index+type.length()+1;
            if (offset >= text.length()) {
                toast(R.string.scanner_retry);
                return null;
            }
            return text.substring(offset);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }



}
